var apiHost = wx.getStorageSync("apiHost"); //请求地址
var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

var AppidFlag = wx.getStorageSync('AppidFlag');


// 60秒倒计时
var countdown = 60;
var settime = function (that) {
  if (countdown == 0) {
    that.setData({
      is_show: true
    })
    countdown = 60;
    return;
  } else {
    that.setData({
      is_show: false,     //判断倒计时
      last_time: countdown
    })
    countdown--;
  }
  setTimeout(function () {
    settime(that)
  }, 1000)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderListheight: 0,      //订单盒子高度
    array: ['微信支付'],    //支付方式选择框
    isUserPoint: '0',       //是否使用U币
    index: 0,             //tab切换
    is_show: true,        //是否展示
    isModal: false,       //余额支付手机验证
    addressId: '',         //地址id
    inputValue: '',        //余额支付验证框
    addressFlag: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var skuidcounts = options.skuidcounts;
    var address = options.address;

    /** 
     * 选择收货地址
    */
    if (options.address) {
      var addressFlag = JSON.parse(address);
      that.setData({
        addressFlag: addressFlag
      })
    }

    // skuidcounts = 'd682b09d449d497d954b1b1d6bff47fd:1';
    var token = wx.getStorageSync('token');             //用户的token信息
    var openid = wx.getStorageSync('openid');           //用户的openId
    var phone = wx.getStorageSync('phone');             //用户手机号

    that.paydetail(token, skuidcounts);
    that.getBalance(token);

    that.setData({
      token: token,
      skuidcounts: skuidcounts,
      openid: openid,
      phone: phone
    })



    that.orderListheight();
  },

  /**
   * 获取用户余额
   */
  getBalance: function (token) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/balance", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          //添加展示用户余额
          var balance = res.data.data.balance;
          var array = that.data.array;
          array.push('余额支付（¥' + balance + '）');
          that.setData({
            array: array
          });
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 支付详情页
   */
  paydetail: function (token, skuIdCounts) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/userspay/paydetail", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        skuIdCounts: skuIdCounts
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {

          var isUsePoint = res.data.data.isUsePoint;
          var pointCout = res.data.data.pointsAmount;
          var addressId = res.data.data.usersAddrVo.id;

          var addressFlag = that.data.addressFlag;
          console.log(addressFlag)
          if (addressFlag == '') {
            that.setData({
              usersAddrVo: res.data.data.usersAddrVo,
              addressId: addressId
            })
          } else {
            that.setData({
              usersAddrVo: addressFlag,
              addressId: addressFlag.id
            })
          }
          //计算实付款 
          that.calActualMoney(token, skuIdCounts, '0', pointCout);
          that.setData({
            paydetail: res.data.data,
            point: res.data.data.points,
            pointsAmount: pointCout
          })
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 计算U币
   */
  pointsChange: function (e) {
    var that = this;
    var token = that.data.token;
    var skuidcounts = that.data.skuidcounts;
    var pointCout = that.data.pointsAmount;
    var isUserPoint = 1;
    if (e.detail.value) {
      isUserPoint = 1;
    } else {
      isUserPoint = 0;
    }
    that.setData({
      isUserPoint: isUserPoint
    })

    that.calActualMoney(token, skuidcounts, isUserPoint, pointCout)
  },

  /**
   * 计算实付款
   */
  calActualMoney: function (token, skuIdCounts, isUserPoint, pointCout) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/orders/calActualMoney", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        skuIdCounts: skuIdCounts,
        isUsePoint: isUserPoint,
        pointCout: pointCout
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {

          that.setData({
            actualPay: res.data.data.actualPay
          })

        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 调用提交订单方法
   */
  submitOrderMethod: function () {
    var that = this;

    var token = that.data.token;              //token
    var skuidcounts = that.data.skuidcounts;  //sku
    var isUserPoint = that.data.isUserPoint;  //是否使用惠金币
    var point = that.data.point;              //使用抵扣积分数量
    var addressId = that.data.addressId;      //地址id
    var actualMoney = that.data.actualPay;    //实付款

    if (addressId == '') {
      that.showMsg('请选择收货地址', 'none');
    } else {
      that.submitOrder(token, skuidcounts, isUserPoint, point, addressId, actualMoney);
    }

  },

  /**
   * 提交订单(获取订单号)
   */
  submitOrder: function (token, skuIdCounts, isUserPoint, point, addressId, actualMoney) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/userspay/submitOrder", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        skuIdCounts: skuIdCounts,
        isUsePoints: isUserPoint,
        point: point,
        id: addressId,
        actualMoney: actualMoney
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          var orderNo = res.data.data;
          that.setData({
            orderNo: orderNo
          });
          that.ifPay(orderNo, token); //判断支付方式
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 判断支付方式
   */
  ifPay: function (orderNo, token) {
    var that = this;
    var index = that.data.index;   //支付方式
    console.log(index)
    if (index == 0) {
      that.getWxPay(orderNo, token);
    } else {
      this.setData({
        isModal: true
      })
    }
  },

  /**
   * 调用微信支付
   */
  getWxPay: function (orderNo, token) {
    var that = this;
    var openid = that.data.openid;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/orders/xcx/pay", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        orderNo: orderNo,
        openId: openid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          console.log(res)
          that.wxPay(res.data.data, orderNo)
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 获取验证码
   */
  getCode: function () {
    var that = this;
    var token = that.data.token;

    // 将获取验证码按钮隐藏60s，60s后再次显示
    that.setData({
      is_show: (!that.data.is_show)  //false
    })
    settime(that);  //倒计时

    that.sendCode(token)//发送验证码
  },

  /**
   * 发送支付验证码
   */
  sendCode: function (token) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/login/payCode",
      data: {
        token: token,
        appId: AppidFlag,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.showMsg(msg, 'success');
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 验证码输入框
   */
  getCodeValue: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  /**
   * 余额支付确认按钮
   */
  cancelorders: function () {
    var that = this;
    var token = that.data.token;
    var orderNo = that.data.orderNo;
    var code = that.data.inputValue;

    if (code == '') {
      that.showMsg('请输入验证码', 'none');
    } else {
      that.banlancePay(token, orderNo, code);
    }
  },

  /**
   * 调起微信支付
   */
  wxPay: function (respon, orderNo) {
    //调支付接口
    wx.requestPayment({
      appId: respon.appId,
      timeStamp: respon.timeStamp,
      nonceStr: respon.nonceStr,
      'package': respon.package,
      signType: respon.signType,
      paySign: respon.paySign,
      'success': function (res) {
        //下单成功后跳转到订单详情页
        wx.navigateTo({
          url: '../orderDetail/orderDetail?orderNo=' + orderNo,
        })
      },
      'fail': function (res) {
      }
    })
  },

  /**
   * 余额支付
   */
  banlancePay: function (token, orderNo, code) {
    var that = this;
    var openid = that.data.openid;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/banlance/pay", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        orderNo: orderNo,
        code: code
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          wx.navigateTo({
            url: '../orderDetail/orderDetail?orderNo=' + orderNo,
          })
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 计算高度
   */
  orderListheight: function () {
    var that = this;
    var query = wx.createSelectorQuery();

    var userInfoConHeight = "";
    var fillOrderBotConHeight = "";
    var ubCon = "";

    query.select('#userInfoCon').boundingClientRect()
    query.select('#fillOrderBotCon').boundingClientRect()

    query.exec(function (res) {
      userInfoConHeight = res[0].height;
      fillOrderBotConHeight = res[1].height;

      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            orderListheight: res.windowHeight - userInfoConHeight - fillOrderBotConHeight
          });
        }
      });
    });
  },

  /**
   * 支付方式选择器
   */
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },

  /**
   * 跳转地址集合
   */
  goReceivingAddress: function () {
    wx.navigateTo({
      url: "../../personalCenter/receivingAddress/receivingAddressList/receivingAddressList",
    })
  },

  /**
   * 弹窗取消
   */
  cancel: function () {
    this.setData({
      isModal: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 提示信息
   */
  showMsg: function (msg, icon) {
    wx.showToast({
      title: msg,
      icon: icon,
      duration: 2000,
      mask: true
    });
  },
})